package com.lenovo.nova.util.network;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import com.lenovo.nova.util.debug.MyOldLog;
import com.lenovo.nova.util.network.NetworkHelper.Method;
import com.lenovo.nova.util.network.NetworkHelper.NetworkManager;

/**
 * apache 联网的底层处理
 * @author liuzhd
 */
public class NetworkManagerApache implements NetworkManager{
	protected static final String RESPONDHEAD_COOKIE = "Set-Cookie";
	private HttpClient httpClient;
	private HttpRequestBase httpRequest;
	private HttpPost httpPost = new HttpPost();
	private HttpGet httpGet = new HttpGet();

	/**
	 * 网络超时时间
	 */
	private static final int CONNECT_TIMEOUT = 120 * 1000;

	/**
	 * 读取超时时间
	 */
	private static final int READ_TIMEOUT = 120 * 1000;


	public NetworkManagerApache() {
		httpClient = getApacheClient();
	}

	/**
	 * @param isPost -- 判断是否是post请求（暂时只支持get和post两种）
	 * @param url
	 * @param requestHead -- 请求的消息报头
	 * @param postBody -- 请求正文
	 * @return
	 * @throws Exception
	 */
	public HttpResponse getResponse(boolean isPost, String url, List<BasicNameValuePair> requestHead, List<BasicNameValuePair> postBody) {
		// 接受服务器的回应
		
		if (isPost) {
			httpRequest = httpPost;
			if (postBody != null) {
				try {
					((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(postBody, HTTP.UTF_8));
				} catch (UnsupportedEncodingException e) {
					MyOldLog.error(this, "URL格式化错误   postBody is " + postBody + "   " + e);
					// e.printStackTrace();
				}
			}
		} else {
			httpRequest = httpGet;
		}
		String encodeUri = url.trim();
        encodeUri = encodeUri.replaceAll(" ", "%20");
		httpRequest.setURI(URI.create(encodeUri));
		
		if (requestHead != null) {
			for (BasicNameValuePair basicNameValuePair : requestHead) {
				httpRequest.addHeader(basicNameValuePair.getName(), basicNameValuePair.getValue());
			}
		}

		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpRequest);
		} catch (UnknownHostException e) {
			MyOldLog.error(this, "getResponse(): UnknownHostException " + e + "  没有网络 连接");
		} catch (ConnectTimeoutException e){
			MyOldLog.e("ConnectTimeoutException " + e);
		} catch (Exception e) {
			MyOldLog.error(this, "getResponse(): IOException " + e);
		}
		
		return httpResponse;
	}

	/**
	 * 关闭连接
	 */
	public void cloaseApachConn(){
		httpClient.getConnectionManager().shutdown();
	}
	
	/**
	 *获取apache的客户端
	 * @return
	 */
	private HttpClient getApacheClient() {
		HttpParams httpParamas = new BasicHttpParams();
		// 设置超时时间
		HttpConnectionParams.setConnectionTimeout(httpParamas, CONNECT_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParamas, READ_TIMEOUT);
		return new DefaultHttpClient(httpParamas);
	}
	
	

	@Override
	public HttpResponse connect(int method, String url, Map<String, String> requestHead, Map<String,String> postBody) {
		List<BasicNameValuePair> heads= null; 
		List<BasicNameValuePair> bodys = null;
		if(requestHead != null){
			heads = new ArrayList<BasicNameValuePair>();
			Iterator<Entry<String, String>> it = requestHead.entrySet().iterator();
			for (Iterator<Entry<String, String>>  iterator = it; iterator.hasNext();) {
				 Entry<String, String> pair = iterator.next();
				heads.add(new BasicNameValuePair(pair.getKey(), pair.getValue()));
			}
		}
		
		if(postBody != null){
			bodys = new ArrayList<BasicNameValuePair>();
			Iterator<Entry<String, String>> it = postBody.entrySet().iterator();
			while(it.hasNext()){
				Entry<String, String>  pair = it.next();
				bodys.add(new BasicNameValuePair(pair.getKey(), pair.getValue()));
			}
		}
		
		HttpResponse response = getResponse(method == Method.POST, url, heads,bodys);
		return response;
	}
}


